package at.ac.thornwishstalon.ocrapp.main.fragments;


import java.util.ArrayList;


import java.util.concurrent.ExecutionException;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import at.ac.thornwishstalon.ocrapp.R;
import at.ac.thornwishstalon.ocrapp.ocr.TesseractResultWrapper;
import at.ac.thornwishstalon.ocrapp.ocr.TesseractTask;
import at.ac.thornwishstalon.ocrapp.ocr.TesseractTaskParamWrapper;
import at.ac.thornwishstalon.ocrapp.pic.OCRAPPView;
import at.ac.thornwishstalon.ocrapp.pic.preferences.PicPreferenceActivity;

/**
 * 
 * @author fry
 *
 */

public class ImageFragment extends Fragment implements OnSharedPreferenceChangeListener{
	private final String TAG= "imageFragment";
	public final String IMAGE_URI= "ocrapp_image_uri";
	private final String PREFS="at.ac.ocrap.prefs";

	private OCRAPPView view;
	private Button accept;
	private Button cancel;
	
	private boolean showBB;
	private boolean showTL;
	private boolean showRE;
	private RectF selection;
	
	private String imageUri;
	private ArrayList<Rect> bb;
	private ArrayList<Rect> re;
	private ArrayList<Rect> tl;
	private MenuItem cloud;
	private MenuItem crop;
	
	private ProgressDialog dialog;
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
		

		SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
		sharedPref.registerOnSharedPreferenceChangeListener(this);


		showBB = sharedPref.getBoolean(PicPreferenceActivity.SHOW_CHAR_BOUNDING_BOXES, false);
		showTL = sharedPref.getBoolean(PicPreferenceActivity.SHOW_TEXTLINES, false);
		showRE = sharedPref.getBoolean(PicPreferenceActivity.SHOW_REGIONS, false);



		sharedPref= getActivity().getSharedPreferences(PREFS, 0);
		sharedPref.registerOnSharedPreferenceChangeListener(this);
		imageUri= sharedPref.getString(IMAGE_URI, "");

	}
	
	
	

	@Override
	public void onPause() {
		Log.d(TAG, "onPause");
		// TODO Auto-generated method stub
		super.onPause();
		
	//	lastM= view.getCurrMatrix();
		//onSaveInstanceState(new Bundle());
		if(view.InRecMode()) 
			selection= view.getSelectionRec();
		
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		view.setImageUri(Uri.parse(imageUri));
		Log.d(TAG, "onResume");
		
		view.setBB(bb);
		view.setRE(re);
		view.setTL(tl);
		if(selection!=null){
			view.setRecMode(true);
			view.setSelection(selection);
			accept.setVisibility(View.INVISIBLE);
			cancel.setVisibility(View.INVISIBLE);
		}
		view.invalidate();
		
		
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle bundle) {
		// TODO Auto-generated method stub
		Log.d(TAG, "onCreateView");
	//	TouchSurfaceView mview= new TouchSurfaceView(this.getActivity());
		
		
		
		View mview= inflater.inflate(R.layout.main_fragment_image, container,false);
		view= (OCRAPPView) mview.findViewById(R.id.touchImageView1);
		//view.setImageUri(Uri.parse(imageUri));
		view.setShow(showBB, showRE, showTL);
		
		accept= (Button) mview.findViewById(R.id.image_accept);
		cancel= (Button) mview.findViewById(R.id.image_cancel);
		
		accept.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				
				view.finalizeRect();
				dialog= new ProgressDialog(getActivity());
				dialog.setTitle(R.string.tess_task_progressbar_title);
				dialog.setMessage(getString(R.string.tess_task_progressbar_message));
				dialog.setIndeterminate(true);
				dialog.setCancelable(false);
				dialog.show();
				
				doOCR();
				accept.setVisibility(View.INVISIBLE);
				cancel.setVisibility(View.INVISIBLE);
				view.setRecMode(false);
				view.invalidate();
				
			}
		});
		
		cancel.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				
				view.discardRect();
				view.setRecMode(false);
				accept.setVisibility(View.INVISIBLE);
				cancel.setVisibility(View.INVISIBLE);
				view.setRecMode(false);
				view.invalidate();
				
			}
		});
		
		if(bundle!=null){
			Log.d(TAG, "bundle not null");
			view.setImageUri(Uri.parse(imageUri));
			
			view.invalidate();
		}
		
		
		return mview;
	}
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.main_fragment_image, menu);

		//MenuItem item = menu.findItem(R.id.main_image_fragment_menu_source);
		//ShareActionProvider provider = (ShareActionProvider) item.getActionProvider();
		//startActivityForResult(Intent.createChooser(intent, "Select Image"), 726104);

		//provider.setShareIntent(intent);
		//provider.setShareHistoryFileName(null);

	}


	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case R.id.main_image_fragment_menu_doOCR:
			
			Log.d(TAG, "doOCR");

			if(view.InRecMode()){
				view.finalizeRect();
				dialog= new ProgressDialog(getActivity());
				dialog.setTitle(R.string.tess_task_progressbar_title);
				dialog.setMessage(getString(R.string.tess_task_progressbar_message));
				dialog.setIndeterminate(true);
				dialog.setCancelable(false);
				dialog.show();
				doOCR();
				accept.setVisibility(View.INVISIBLE);
				cancel.setVisibility(View.INVISIBLE);
				view.invalidate();
			}
			else {
				dialog= new ProgressDialog(getActivity());
				dialog.setTitle(R.string.tess_task_progressbar_title);
				dialog.setMessage(getString(R.string.tess_task_progressbar_message));
				dialog.setIndeterminate(true);
				dialog.setCancelable(false);
				dialog.show();
				doOCR();
			}

			break;
		case R.id.main_image_fragment_menu_doRectangle:
			item.setCheckable(true);
			if(view.InRecMode()){
				item.setChecked(false);
				accept.setVisibility(View.INVISIBLE);
				cancel.setVisibility(View.INVISIBLE);
			}
			else{
				item.setChecked(true);
				accept.setVisibility(View.VISIBLE);
				cancel.setVisibility(View.VISIBLE);
			}
			Log.d(TAG, "doRec");
			Log.i(TAG, "mode: +"+!view.InRecMode());
			view.setRecMode(!view.InRecMode());
			view.invalidate();

			break;

		}

		return true;
	}

	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {

		Log.d(TAG, "prefs changed");

		if(key.equals(PicPreferenceActivity.SHOW_CHAR_BOUNDING_BOXES)){	
			showBB = sharedPreferences.getBoolean(PicPreferenceActivity.SHOW_CHAR_BOUNDING_BOXES, false);
			view.setShow(showBB, showRE, showTL);
			view.invalidate();
		}
		if(key.equals(PicPreferenceActivity.SHOW_REGIONS)){
			showRE = sharedPreferences.getBoolean(PicPreferenceActivity.SHOW_REGIONS, false);
			view.setShow(showBB, showRE, showTL);
			view.invalidate();
		}
		if(key.equals(PicPreferenceActivity.SHOW_TEXTLINES)){
			showTL = sharedPreferences.getBoolean(PicPreferenceActivity.SHOW_TEXTLINES, false);
			view.setShow(showBB, showRE, showTL);
			view.invalidate();
		}
		if(key.equals(IMAGE_URI)){
			Log.d(TAG,"uri changed, refresh view!");
			imageUri=sharedPreferences.getString(IMAGE_URI, "");
			view.setImageUri(Uri.parse(imageUri));

			cloud.setEnabled(true);
			cloud.setIcon(R.drawable.ocr);
			crop.setEnabled(true);
			crop.setIcon(R.drawable.images_crop);

			SharedPreferences.Editor editor= sharedPreferences.edit();
			editor.putString("ocrapp_text", "");
			editor.commit();
			
			bb=null;
			tl=null;
			re=null;

		}

	}


	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		Log.d(TAG, "onActivityCreated");
		if(savedInstanceState!=null){
		
			view.setImageUri(Uri.parse(imageUri));
			
		}
	}
	 
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		Log.d(TAG,"onSaveInstanceState");
		
		//float[] saveM= new float[9];

		//view.getCurrMatrix().getValues(saveM);

		//outState.putFloatArray("img_matrix", saveM);

		 
	}


	public String getTAG() {
		return TAG;
	}

	

	@Override
	public void onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
		Log.d(TAG, "onprepareOptionsMenu");
		crop=menu.findItem(R.id.main_image_fragment_menu_doRectangle);
		cloud=menu.findItem(R.id.main_image_fragment_menu_doOCR);
		if(imageUri.equals("")){

			cloud.setEnabled(false);
			cloud.setIcon(R.drawable.ocr_dark);
			crop.setEnabled(false);
			crop.setIcon(R.drawable.images_crop_dark);
		}else{
			cloud.setEnabled(true);
			cloud.setIcon(R.drawable.ocr);
			crop.setEnabled(true);
			crop.setIcon(R.drawable.images_crop);
		}
	}
	
	private void doOCR(){
		TesseractResultWrapper result;
		//ProgressDialog pd= new ProgressDialog(getActivity(), ProgressDialog.STYLE_SPINNER);
		//pd.setMessage(getActivity().getString(R.string.tess_task_progressbar_message));
		//pd.setTitle(getActivity().getString(R.string.tess_task_progressbar_title));
		//pd.setCancelable(false);
		//pd.show();

		
		TesseractTask task= new TesseractTask(getActivity(),dialog);
		
		try {

			RectF rect;
			if(view.isRecSet() && view.InRecMode()){
				rect=view.getSelectionRec();
			}
			else rect=null;
			
			TesseractTaskParamWrapper param = new TesseractTaskParamWrapper(Uri.parse(imageUri), rect);
			result=task.execute(param).get();

			//Toast.makeText(this, result.getText(), Toast.LENGTH_LONG).show();
			bb=result.getCharacterBoundaryBoxes();
			tl= result.getTextlines();
			re= result.getRegions();

			//view.setText(result.getText());
			view.setBB(result.getCharacterBoundaryBoxes());
			view.setRE(result.getRegions());
			view.setTL(result.getTextlines());
			view.invalidate();
			view.discardRect();
			view.setRecMode(false);

			SharedPreferences sharedPref= getActivity().getSharedPreferences(PREFS, 0);
			SharedPreferences.Editor editor= sharedPref.edit();
			editor.putString("ocrapp_text", result.getText());
			editor.commit();

			Toast.makeText(getActivity(), getActivity().getString(R.string.ocr_done), Toast.LENGTH_LONG).show();
			

		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	
	



}
